<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto"
      :rules="rules">
      <el-form-item label="用户昵称" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户昵称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="用户手机号" prop="userMobilePhone">
        <el-input size="mini" v-model="queryParams.userMobilePhone" placeholder="请输入用户手机号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="性别" prop="userSex">
        <el-radio-group v-model="queryParams.userSex">
          <el-radio label="0">男</el-radio>
          <el-radio label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <br />
      <el-form-item label="注册时间" prop="createTime">
        <el-date-picker v-model="createTimeStart" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item prop="beginSportScore" label="积分范围">
        <el-input size="mini" v-model="queryParams.beginSportScore" placeholder="请输入起始积分" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item prop="endSportScore">
        <el-input size="mini" v-model="queryParams.endSportScore" placeholder="请输入结束积分" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="userList">
      <!--      <el-table-column type="selection" width="55" align="center" />多选框-->
      <el-table-column width="50px" label="编号" align="center" prop="userId" />
      <el-table-column width="150px" label="昵称" align="center" prop="userName" />
      <el-table-column width="50px" label="性别" align="center" prop="userSex" />
      <el-table-column width="150px" label="运动级别" align="center" prop="userScore" />
      <el-table-column label="用户头像图片" align="center" prop="userTitleImg">
        <template slot-scope="scope">
          <img :src="getImage(scope.row.userTitleImg)" class="img-square img-lg" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="sportUserDetail(scope.row)"
            v-hasPermi="['system:user:edit']">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']">我的笔记</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']">我的点赞</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']">我的关注</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']">我的勋章</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:user:remove']">绑定的音乐</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-button plain @click="firstPage()">首页</el-button>
      <pagination class="pagination" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize" @pagination="getList" />
      <el-button plain @click="endPage()">末页</el-button>
    </div>
    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px" :disabled="formHidden">
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="userMobilePhone">
          <el-input v-model="form.userMobilePhone" placeholder="请输入用户手机号" />
        </el-form-item>
        <el-form-item label="运动积分" prop="userScore">
          <el-input v-model="form.userScore" placeholder="请输入用户运动积分" />
        </el-form-item>
        <el-form-item label="用户性别" prop="userSex">
          <el-input v-model="form.userSex" placeholder="请输入用户性别" />
        </el-form-item>
        <el-form-item label="用户身高" prop="userHeight">
          <el-input v-model="form.userHeight" placeholder="请输入用户身高" />
        </el-form-item>
        <el-form-item label="用户体重" prop="userWeight">
          <el-input v-model="form.userWeight" placeholder="请输入用户体重" />
        </el-form-item>
        <el-form-item label="头像图片" prop="userTitleImg">
          <div>
            <img :src="getImage(form.userTitleImg)" class="img-square img-lg">
          </div>
        </el-form-item>
        <el-form-item label="封面图片" prop="userImg">
          <img v-bind:src="getImage(form.userImg)" class="img-square img-lg" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-show="buttonHidden">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser } from "@/api/system/sportuser"
import * as download from '@/plugins/download'
import { getImage } from "../../../utils/request"

export default {
  name: "User",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      //模糊查询日期范围
      createTimeStart: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        userSex: null,
        userMobilePhone: null,
        userScore: null,
        userHeight: null,
        userWeight: null,
        userTitleImg: null,
        userImg: null,
        deleteFlag: null,
        beginSportScore: null,
        endSportScore: null,
        version: null
      },
      // 表单参数
      form: {},
      //弹出框修改按钮隐藏变量
      buttonHidden: false,
      //弹出框控件禁止操作变量
      formHidden: true,
      // 表单校验
      rules: {
        userName: [
          { message: "用户昵称不能为空", trigger: "blur", max: 50 }
        ],
        userMobilePhone: [
          { message: "手机号11位", trigger: "change", max: 11 }
        ],
        // 添加积分范围校验规则
        beginSportScore: [
          {
            validator: function (rule, value, callback) {
              if (!value) {
                callback(); // 如果为空，不校验
                return;
              }
              const num = Number(value);
              if (isNaN(num) || num <= 0 || num >= 1000000) {
                callback(new Error('起始积分必须为大于0且小于1000000的数字'));
              } else {
                // 检查是否大于结束积分
                const endScore = this.queryParams.endSportScore;
                if (endScore && num > Number(endScore)) {
                  callback(new Error('起始积分不能大于结束积分'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'blur'
          }
        ],
        endSportScore: [
          {
            validator: function (rule, value, callback) {
              if (!value) {
                callback(); // 如果为空，不校验
                return;
              }
              const num = Number(value);
              if (isNaN(num) || num <= 0 || num >= 1000000) {
                callback(new Error('结束积分必须为大于0且小于1000000的数字'));
              } else {
                // 检查是否小于起始积分
                const beginScore = this.queryParams.beginSportScore;
                if (beginScore && Number(beginScore) > num) {
                  callback(new Error('结束积分不能小于起始积分'));
                } else {
                  callback();
                }
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getList()
    // 绑定校验规则的 this 指向
    this.rules.beginSportScore[0].validator = this.rules.beginSportScore[0].validator.bind(this)
    this.rules.endSportScore[0].validator = this.rules.endSportScore[0].validator.bind(this)
  },
  methods: {
    /** 查询用户列表 */
    /**
     *       listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.userList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
     */
    getList() {
      this.loading = true
      listUser(this.addDateRange(this.queryParams, this.createTimeStart)).then(response => {
        const sportUserLists = response.rows
        sportUserLists.map(function (item) {
          if (item.userSex == 1) {
            item.userSex = '女'
          } else {
            item.userSex = '男'
          }
        })
        this.userList = sportUserLists
        this.total = response.total
        this.loading = false
      })
    },
    //首页方法
    firstPage() {
      this.queryParams.pageNum = 1;
      this.getList()
    },
    //末页方法
    endPage() {
      let totalPage = Number(this.total / this.queryParams.pageSize)
      console.log(totalPage);

      if (totalPage % 1 != 0) {
        totalPage = Math.floor(totalPage) + 1
      }
      this.queryParams.pageNum = totalPage;
      this.getList()
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        userName: null,
        userSex: null,
        userMobilePhone: null,
        userScore: null,
        userHeight: null,
        userWeight: null,
        userTitleImg: null,
        userImg: null,
        createTime: null,
        updateTime: null,
        deleteFlag: null,
        createBy: null,
        updateBy: null,
        version: null
      }

      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // 先进行表单校验
      this.$refs.queryForm.validate((valid) => {
        if (valid) {
          // 校验通过，执行查询
          this.queryParams.pageNum = 1
          this.getList()
          this.$modal.msgSuccess("查询成功，已显示符合条件的用户信息")
        } else {
          // 校验失败，显示错误信息
          this.$modal.msgError("查询失败，请检查输入的数据格式")
          return false;
        }
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.beginSportScore = null
      this.queryParams.endSportScore = null
      this.createTimeStart = []  // 清空日期范围
      this.queryParams.userSex = null  // 显式清空性别选择
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // // 多选框选中数据
    // handleSelectionChange(selection) { //参数代表当前选中的行的数据
    //   this.ids = selection.map(item => item.userId)
    //   this.single = selection.length!==1
    //   this.multiple = !selection.length
    // },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加用户"
    },
    /** 用户详情按钮操作 */
    sportUserDetail(row) {
      this.reset()
      this.formHidden = true
      this.buttonHidden = false
      // const userId = row.userId || this.ids
      const userId = row.userId
      getUser(userId).then(response => {
        this.form = response.data
        this.form.userHeight = this.form.userHeight + "CM"
        this.form.userWeight = this.form.userWeight + "kg"
        this.open = true
        this.title = "用户详情信息"
        console.log(this.form);


      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
        return delUser(userIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped lang="scss">
.pagination-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.pagination {
  margin: 0 10px;
}
</style>
